package com.ggh.jinjilive.ui.mall.shop;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.services.core.PoiItem;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.ggh.jinjilive.BaseApplication;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.databinding.ActivityShopModificationBinding;
import com.ggh.jinjilive.listener.AddOnClickListener1;
import com.ggh.jinjilive.mobile.mall.shop.ShopMessageMobile;
import com.ggh.jinjilive.ui.BaseActivity;
import com.ggh.jinjilive.ui.mall.shop.adapter.ShopModificationAdapter;
import com.ggh.jinjilive.ui.map.NearMapActivity;
import com.ggh.jinjilive.utils.ARouterUtils;
import com.ggh.jinjilive.utils.CommonUtils;
import com.ggh.jinjilive.utils.GlideEngine;
import com.ggh.jinjilive.views.GridItemDecoration;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.style.cityjd.JDCityConfig;
import com.lljjcoder.style.cityjd.JDCityPicker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 修改店铺
 */
@Route(path = ARouterUtils.ShopModificationActivity)
public class ShopModificationActivity extends BaseActivity<ActivityShopModificationBinding> implements View.OnClickListener {
    //VM
    private ShopViewModel shopViewModel;
    //传输过来的店铺信息
    private ShopMessageMobile shopMessageMobile;
    //添加图片
    private ShopModificationAdapter shopModificationAdapter;
    //店铺图片
    private String picture;
    //店铺背景图
    private List<String> imglist;
    //经纬度
    private PoiItem poiItem;
    @Override
    public void initCreate() {
        super.initCreate();
        ImmersionBar.with(this).keyboardEnable(true).init();
        BaseApplication.getInstance().getAppComponent().doInjectionMain(this);
        shopViewModel = new ViewModelProvider(this,viewModelFactory).get(ShopViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_shop_modification;
    }


    @Override
    public void initParam() {
        super.initParam();
        //传输过来的店铺信息
        shopMessageMobile = (ShopMessageMobile) getIntent().getSerializableExtra("ShopMessageMobile");
    }

    @Override
    public void initView() {
        super.initView();
        //店铺名称
        setWhiteActionBarStyle("店铺管理",true,true);
        //获取状态栏高度
        binding.llSpacing.setPadding(0, BarUtils.getStatusBarHeight(),0,0);
        //适配器
        shopModificationAdapter = new ShopModificationAdapter();
        binding.rv.setAdapter(shopModificationAdapter);
        binding.rv.setLayoutManager(new GridLayoutManager(mContext,3));
        binding.rv.addItemDecoration(new GridItemDecoration(3, ConvertUtils.dp2px(10),true));
    }

    @Override
    public void initData() {
        super.initData();
        //传输过来的店铺信息
        if(null != shopMessageMobile){
            //店铺图片
            Glide.with(binding.riv).load(shopMessageMobile.getImg()).into(binding.riv);
            //店铺集合图
            shopModificationAdapter.setAdd(shopMessageMobile.getString());
            imglist = shopMessageMobile.getString();
            //店铺名称
            binding.etName.setText(shopMessageMobile.getName());
            //营业时间
            binding.tvStartTime.setText(shopMessageMobile.getStart_time());
            binding.tvEndTime.setText(shopMessageMobile.getEnd_time());
            //联系电话
            binding.etMobile.setText(shopMessageMobile.getMobile());
            //联系人
            binding.etUser.setText(shopMessageMobile.getUser());
            //店铺地址
            binding.tvSAddress.setText(shopMessageMobile.getS_address());
            //详细地址
            binding.etAddress.setText(shopMessageMobile.getAddress());
            //运费
            binding.etTransportFee.setText(shopMessageMobile.getTransport_fee());
            //请输入店铺公告
            binding.etContent.setText(shopMessageMobile.getContent());
        }else {
            //店铺集合图
            imglist = new ArrayList<>();
        }
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //提交
        binding.managementButton.setOnClickListener(this);
        //店铺图片
        binding.riv.setOnClickListener(this);
        //开始时间
        binding.tvStartTime.setOnClickListener(this);
        //结束时间
        binding.tvEndTime.setOnClickListener(this);
        //店铺地址
        binding.tvSAddress.setOnClickListener(this);
        //定位
        binding.imgPositioning.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.management_Button://提交
                Map<String, Object> map = new HashMap<>();
                //店铺名称
                String etName = binding.etName.getText().toString();
                if(TextUtils.isEmpty(etName)){
                    ToastUtils.make().show("请输入店铺名称");
                    return;
                }
                map.put("name", etName);
                //营业时间开始时间
                String start_time = binding.tvStartTime.getText().toString();
                if(TextUtils.isEmpty(start_time)){
                    ToastUtils.make().show("请选择营业开始时间");
                    return;
                }
                map.put("start_time", start_time);
                //营业时间结束时间
                String end_time = binding.tvEndTime.getText().toString();
                if(TextUtils.isEmpty(end_time)){
                    ToastUtils.make().show("请选择营业结束时间");
                    return;
                }
                map.put("end_time", end_time);
                //联系电话
                String mobile = binding.etMobile.getText().toString();
                if(TextUtils.isEmpty(mobile)){
                    ToastUtils.make().show("请输入联系电话");
                    return;
                }
                map.put("mobile", mobile);
                //联系人
                String user = binding.etUser.getText().toString();
                if(TextUtils.isEmpty(user)){
                    ToastUtils.make().show("请输入联系人");
                    return;
                }
                map.put("user", user);
                //店铺图片
                if(TextUtils.isEmpty(picture)){
                    if(null != shopMessageMobile){
                        map.put("img", shopMessageMobile.getImg());
                    }else {
                        ToastUtils.make().show("请上传图片");
                        return;
                    }
                }else {
                    map.put("img", picture);
                }
                if(imglist.size() == 3){
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i =0; i< imglist.size(); i++){
                        stringBuilder.append(imglist.get(i));
                        if (i != imglist.size()-1){
                            stringBuilder.append(",");
                        }
                    }
                    map.put("imglist", stringBuilder.toString());
                }else {
                    ToastUtils.make().show("请上传3张图片");
                    return;
                }
                String content = binding.etContent.getText().toString();
                if(TextUtils.isEmpty(content)){
                    ToastUtils.make().show("请输入店铺公告");
                    return;
                }
                map.put("content", content);
                if(null != poiItem){
                    map.put("lng", poiItem.getLatLonPoint().getLongitude());
                    map.put("lat", poiItem.getLatLonPoint().getLatitude());
                    map.put("address", poiItem.getSnippet());
                    map.put("s_address", poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName());
                }else {
                    if(null != shopMessageMobile){
                        map.put("lng", shopMessageMobile.getLng());
                        map.put("lat", shopMessageMobile.getLat());
                        map.put("address", shopMessageMobile.getAddress());
                        map.put("s_address", shopMessageMobile.getS_address());
                    }
                }
                String freight = binding.etTransportFee.getText().toString();
                if(TextUtils.isEmpty(freight)){
                    ToastUtils.make().show("请输入运费");
                    return;
                }
                map.put("transport_fee", freight);
                if(null != shopMessageMobile){
                    map.put("tag", shopMessageMobile.getTag());
                }
                shopViewModel.shopStoreStoreEdit(map);
                break;
            case R.id.riv://店铺图片
                EasyPhotos.createAlbum(ShopModificationActivity.this, true,false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快），[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                        .setFileProviderAuthority("com.ggh.jinjilive.fileprovider")//参数说明：见下方`FileProvider的配置`
                        .start(new SelectCallback() {
                            @Override
                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                if(photos.size() > 0){
                                    shopViewModel.uploadimages(photos.get(0).path, new AddOnClickListener1() {
                                        @Override
                                        public void onSkipClicked(Object mObject) {
                                            picture = (String) mObject;
                                            if(null != picture){
                                                //店铺图片
                                                Glide.with(binding.riv).load(picture).into(binding.riv);
                                            }

                                        }
                                    });
                                }
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                break;
            case R.id.tv_start_time://开始时间
                CommonUtils.initTimePicker(mContext,binding.tvStartTime);
                break;
            case R.id.tv_end_time://结束时间
                CommonUtils.initTimePicker(mContext,binding.tvEndTime);
                break;
            case R.id.tv_s_address://店铺地址
                JDCityPicker cityPicker = new JDCityPicker();
                JDCityConfig jdCityConfig = new JDCityConfig.Builder().build();
                jdCityConfig.setShowType(JDCityConfig.ShowType.PRO_CITY_DIS);
                cityPicker.init(this);
                cityPicker.setConfig(jdCityConfig);
                cityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
                    @Override
                    public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                        binding.tvSAddress.setText(province.getName() +"  "+ city.getName() +"  "+  district.getName());
                    }

                    @Override
                    public void onCancel() {

                    }
                });
                cityPicker.showCityPicker();
                break;
            case R.id.img_positioning://定位
                Intent intent = new Intent(mContext, NearMapActivity.class);
                intent.putExtra("shopLocation","店铺");
                startActivityForResult(intent,2111);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 2032){
            poiItem = data.getParcelableExtra("PoiItem");
            if(null != poiItem){
                //店铺地址
                binding.tvSAddress.setText(poiItem.getProvinceName() +"  "+ poiItem.getCityName() +" " + poiItem.getAdName());
                //详细地址
                binding.etAddress.setText(poiItem.getSnippet());

                //店铺地址
                LogUtils.d(new Gson().toJson(poiItem));
            }
        }
    }
}
